package cn.edu.ncu.housinghub.controller.test;

import cn.edu.ncu.housinghub.vo.Result;
import cn.edu.ncu.housinghub.dto.chat.ChatMessageDTO;
import cn.edu.ncu.housinghub.entity.chatsession.ChatMessage;
import cn.edu.ncu.housinghub.entity.chatsession.ChatSession;
import cn.edu.ncu.housinghub.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天功能测试控制器
 * 提供不需要登录验证的测试接口
 */
@RestController
@RequestMapping("/test/chat")
@RequiredArgsConstructor
public class ChatTestController {

    private final ChatService chatService;

    /**
     * 测试创建聊天会话
     * @param requestBody 请求体
     * @return 会话信息
     */
    @PostMapping("/create-session")
    public Result createSession(@RequestBody Map<String, Object> requestBody) {
        try {
            // 直接从请求体获取参数，不验证token
            Long userId1 = Long.valueOf(requestBody.get("userId1").toString());
            Long userId2 = Long.valueOf(requestBody.get("userId2").toString());
            Long houseId = requestBody.get("houseId") != null ? 
                Long.valueOf(requestBody.get("houseId").toString()) : null;
            
            // 创建或获取会话
            ChatSession session = chatService.getOrCreateSession(userId1, userId2, houseId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("sessionId", session.getSessionId());
            result.put("userId1", session.getUserId1());
            result.put("userId2", session.getUserId2());
            result.put("houseId", session.getHouseId());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "会话创建失败: " + e.getMessage());
        }
    }

    /**
     * 测试发送消息
     * @param requestBody 请求体
     * @return 发送结果
     */
    @PostMapping("/send-message")
    public Result sendMessage(@RequestBody Map<String, Object> requestBody) {
        try {
            // 直接从请求体获取参数，不验证token
            Long senderId = Long.valueOf(requestBody.get("senderId").toString());
            Long receiverId = Long.valueOf(requestBody.get("receiverId").toString());
            String content = requestBody.get("content").toString();
            Integer type = requestBody.get("type") != null ? 
                Integer.valueOf(requestBody.get("type").toString()) : 1;
            Long houseId = requestBody.get("houseId") != null ? 
                Long.valueOf(requestBody.get("houseId").toString()) : null;
            
            // 创建消息DTO
            ChatMessageDTO messageDTO = new ChatMessageDTO();
            messageDTO.setReceiverId(receiverId);
            messageDTO.setContent(content);
            messageDTO.setType(type);
            messageDTO.setHouseId(houseId);
            
            // 发送消息
            ChatMessage message = chatService.sendMessage(senderId, messageDTO);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messageId", message.getMessageId());
            result.put("sessionId", message.getSessionId());
            result.put("senderId", message.getSenderId());
            result.put("receiverId", message.getReceiverId());
            result.put("content", message.getContent());
            result.put("sendTime", message.getSendTime());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "消息发送失败: " + e.getMessage());
        }
    }

    /**
     * 测试获取会话消息
     * @param sessionId 会话ID
     * @param page 页码
     * @param size 每页大小
     * @return 消息列表
     */
    @GetMapping("/session/{sessionId}/messages")
    public Result getSessionMessages(
            @PathVariable Long sessionId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            // 获取会话消息
            List<ChatMessage> messages = chatService.getSessionMessages(sessionId, page, size);
            
            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            result.put("page", page);
            result.put("size", size);
            result.put("total", messages.size());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "获取消息失败: " + e.getMessage());
        }
    }

    /**
     * 测试获取用户会话列表
     * @param userId 用户ID
     * @return 会话列表
     */
    @GetMapping("/user/{userId}/sessions")
    public Result getUserSessions(@PathVariable Long userId) {
        try {
            // 获取用户会话列表
            List<ChatSession> sessions = chatService.getUserSessions(userId);
            
            return Result.success(sessions);
        } catch (Exception e) {
            return Result.error(500, "获取会话列表失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     * @return 状态信息
     */
    @GetMapping("/health")
    public Result health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "ok");
        result.put("timestamp", System.currentTimeMillis());
        result.put("message", "聊天测试API正常运行");
        
        return Result.success(result);
    }
}
